package com.template;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.component.domain.*;
import com.component.enumitem.NoteAddTypeEnum;
import com.component.enumitem.NoteContentTypeEnum;
import com.component.enumitem.NoteDataTypeEnum;
import com.component.enumitem.NoteUpdateTypeEnum;
import com.component.service.*;
import com.system.common.ContextUtils;
import com.system.security.IsSecurity;
import com.system.security.SecurityUtil;
import com.system.security.domain.SelfUserEntity;
import com.system.util.EnumToListConverter;
import io.swagger.annotations.ApiModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Max;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Classname IndexController
 * @Description TODO
 * @Date 2023/9/17 1:51
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@Controller
@IsSecurity(isSecurity = false)
@RequestMapping("/")
public class IndexController {

    @GetMapping()
    public String index(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                        @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                        @RequestParam(value = "keyword",defaultValue = "")String keyword,
                        Map<String, Object> map){
        if(pageSize>100){
            pageSize = 100;
        }
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);
        map.put("keyword",keyword);
        return "zhuye";
    }

    @GetMapping("/es")
    public String es(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                     @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                     @RequestParam(value = "keyword",defaultValue = "")String keyword,
                     Map<String, Object> map){
        if(pageSize>100){
            pageSize = 100;
        }
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);
        map.put("keyword",keyword);
        return "es";
    }

    @GetMapping("/list")
    public String list(){
        return "page/list";
    }

    @GetMapping("/login")
    public String login(@RequestParam(value = "html",required = false)String html,
                        Map<String,Object> map) {
        map.put("html",html==null?"":html);
        return "login";
    }

//    @GetMapping("/manager")
//    public String manager(HttpServletResponse response) throws IOException {
//        SelfUserEntity selfUserEntity= SecurityUtil.getSelfUserEntity();
//        if(selfUserEntity==null){
//            response.sendRedirect("/login?html=manager");
//        }
//        return "page/manager";
//    }

    @Autowired
    private MModelService mModelService;

    @GetMapping("/add")
    public String add(HttpServletResponse response,
                      HttpServletRequest request,
                      @RequestParam(value = "channelId",required = false)Integer channelId) throws IOException {
        SelfUserEntity selfUserEntity= SecurityUtil.getSelfUserEntity();
        if(selfUserEntity==null){
            response.sendRedirect("/login?html=add");
        }
        MChannel mChannel=null;

        if(channelId!=null){
            mChannel=mChannelService.getById(channelId);
        }
        if(mChannel!=null){
            request.setAttribute("channelId",channelId);
        }else {
            request.setAttribute("channelId","''");
        }
        if(mChannel!=null && StringUtils.isNotBlank(mChannel.getModelId())){
            //处理模型
            MModel mModel=mModelService.getById(mChannel.getModelId());
            if(mModel != null){
                JSONArray model=JSONArray.parseArray(mModel.getModelJson());
                mModelService.sort(model);
                List<String> mModels=mModelService.getComponentsByArray(model);
                String defalut=mModelService.getModelDefaultValueByArr(model);
                request.setAttribute("model",mModel);
                request.setAttribute("defaultvalue",defalut);
                request.setAttribute("modelData",JSONObject.parseArray(mModel.getModelJson()));
                request.setAttribute("list",mModels);
                return "page/adddatamodel";
            }
        }
        if(mChannel!=null && mChannel.getTextType()!=null){
            List<Map<String,Object>> maps= EnumToListConverter.convert(NoteAddTypeEnum.values(),"type","path");
            Map<String,String> map=maps.stream().collect(Collectors.toMap((e)->(String)e.get("type"), (e)->(String)e.get("path"), (key1, key2) -> key2));
            if(map.containsKey(mChannel.getTextType())){
                return map.get(mChannel.getTextType());
            }
        }
        return "page/add";
    }

    @Autowired
    private NoteService noteService;

    @Autowired
    private ContentService contentService;

    @GetMapping("update")
    public String update(@RequestParam(value = "id",required = false)String id,
                         HttpServletRequest request,
                         Map<String,Object> map) {
        if(id==null || "".equals(id)){
            return "/";
        }
        Note note=noteService.getById(id);
        if(note==null){
            return "/";
        }
        MChannel mChannel=mChannelService.getById(note.getChannelId());
        System.out.println(mChannel.getTextType()+" 111111");
        if(StringUtils.isNotBlank(note.getDatatype()) && note.getDatatype().equals(NoteDataTypeEnum.JSON.getDataType())){
            //处理模型
            Content content=contentService.getContentByNid(note.getId());
            if(content != null){
                JSONObject json=JSONObject.parseObject(ContextUtils.decryptStr(content.getContent()));
                System.out.println(json.toString());
                JSONArray model=json.getJSONArray("model");
                JSONArray array=json.getJSONArray("array");
                if(mChannel!=null){
                    MModel mModel=mModelService.getById(mChannel.getModelId());
                    if(mModel != null){
                        model=mModelService.getModelArray(mModel);
                    }
                }
                mModelService.sort(model);
                String defalutValues=mModelService.getModelDefaultValueByArr(model);
                List<String> mModels=mModelService.getComponentsByArray(model);

                mModelService.getArrayByModelDataType(array,model);
                request.setAttribute("model",JSONObject.toJSONString(model));
                request.setAttribute("defaultvalue",defalutValues);
                request.setAttribute("channelId",note.getChannelId());
                request.setAttribute("dataList",JSONObject.toJSONString(array));
                request.setAttribute("list",mModels);
                request.setAttribute("id",String.valueOf(note.getId()));
                request.setAttribute("title",note.getTitle());
                request.setAttribute("tag",note.getTag());
                return "page/updatedatamodel";
            }
        }
        map.put("id",id);
        if(mChannel!=null && mChannel.getTextType()!=null){
            List<Map<String,Object>> maps= EnumToListConverter.convert(NoteUpdateTypeEnum.values(),"type","path");
            Map<String,String> m=maps.stream().collect(Collectors.toMap((e)->(String)e.get("type"), (e)->(String)e.get("path"), (key1, key2) -> key2));
            if(m.containsKey(mChannel.getTextType())){
                return m.get(mChannel.getTextType());
            }
        }
        return "page/update";
    }

    @GetMapping("/getcontent")
    public String getContent(@RequestParam(value = "id",required = false)Integer id,
                             Map<String, Object> map,
                             HttpServletRequest request,
                             HttpServletResponse response) throws IOException {
        if(id==null ){
            return "/";
        }
        Note note=noteService.getById(id);
        if(note==null){
            return "/";
        }
        if(note.getIsprivate()){
            SelfUserEntity userEntity=SecurityUtil.getSelfUserEntity();
            if(userEntity==null){
               response.sendRedirect("/login?html=getcontent?id="+id);
            }
            if(note.getUserid()!=null){
                if(!note.getUserid().equals(userEntity.getUserId().toString())){
                    //返回告警页面
                    map.put("msg","不可访问页面");
                    return "page/warnnotice";
                }
            }
        }
        MChannel mChannel=mChannelService.getById(note.getChannelId());
        if(StringUtils.isNotBlank(note.getDatatype()) && note.getDatatype().equals(NoteDataTypeEnum.JSON.getDataType())){
            Content content=contentService.getContentByNid(note.getId());
            JSONObject json=JSONObject.parseObject(ContextUtils.decryptStr(content.getContent()));
            JSONArray model=json.getJSONArray("model");
            JSONArray array=json.getJSONArray("array");
            mModelService.sort(model);
            mModelService.getArrayByModelDataType(array,model);
            List<String> getTables=mModelService.getTablesByArray(model);
            request.setAttribute("tables",getTables);
            request.setAttribute("model",JSONObject.toJSONString(model));
            request.setAttribute("array",JSONObject.toJSONString(array));
            request.setAttribute("title",note.getTitle());
            request.setAttribute("updateurl",note.getUpdateUrl());
            return "page/contentdatamodel";
        }
        map.put("id", note.getId());
        if(mChannel!=null && mChannel.getTextType()!=null){
            List<Map<String,Object>> maps= EnumToListConverter.convert(NoteContentTypeEnum.values(),"type","path");
            Map<String,String> m=maps.stream().collect(Collectors.toMap((e)->(String)e.get("type"), (e)->(String)e.get("path"), (key1, key2) -> key2));
            if(m.containsKey(mChannel.getTextType())){
                return m.get(mChannel.getTextType());
            }
        }
        return "page/content";
    }



    @GetMapping("resource")
    public String resource(){
        return "page/resource";
    }

    @GetMapping("channel")
    public String channel(){
        return "page/channellist";
    }

    @GetMapping("system")
    public String system(HttpServletResponse response) throws IOException {
        SelfUserEntity selfUserEntity= SecurityUtil.getSelfUserEntity();
        if(selfUserEntity==null){
            response.sendRedirect("/login?html=manager");
        }
        return "page/system";
    }

    @Autowired
    private MChannelService mChannelService;

    @GetMapping("channeltitle")
    public String channelTitle(HttpServletResponse response,
                                HttpServletRequest request,
                                @RequestParam(value = "channelPath",required = false)String channelPath) throws IOException {
        if(channelPath == null){
            response.sendRedirect("/");
        }
        MChannel mChannel=mChannelService.getMChannelByPath(channelPath);
        if(mChannel == null){
            response.sendRedirect("/");
        }
        request.setAttribute("channel_name",mChannel.getChannelname());
        request.setAttribute("channel_path",channelPath);
        return "page/channeltitlelist";
    }

    @Autowired
    private MMenuService mMenuService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @GetMapping("menumanager/{id}")
    public String menumanager(HttpServletResponse response,
                              HttpServletRequest request,
                              @PathVariable("id")String id) throws IOException {
        SelfUserEntity userEntity=SecurityUtil.getSelfUserEntity();
        if(userEntity==null){

            response.sendRedirect("/login?html=menumanager/"+id);
        }
        if(id==null || "".equals(id)){
            response.sendRedirect("/");
        }
        MMenu mMenu=mMenuService.getById(id);
        if(mMenu==null){
            response.sendRedirect("/");
        }
        String activeName="";
        List<MMenu> menuList=null;
        boolean isExist=false;
        //校验权限
        List<SysRoleMenuEntity> list=sysRoleMenuService.getSysRoleMenuEntityUid(userEntity.getUserId());
        if(list==null || list.size() == 0){
            menuList= Collections.emptyList();
        }else {
            List<Integer> menusIds=list.stream().map(e->Integer.valueOf(String.valueOf(e.getMenuId()))).collect(Collectors.toList());
            List<MMenu> menus=mMenuService.getMMenuList(menusIds);
            if(menus!=null && menus.size() > 0){
                menuList=menus.stream().filter(e->e.getPid().equals(String.valueOf(mMenu.getId()))).distinct().collect(Collectors.toList());
            }
        }
       // List<MMenu> menuList=mMenuService.childrenList(mMenu.getId().toString());
        if(menuList==null){
            menuList= Collections.emptyList();
        }
        if(menuList.size() > 0){
            activeName=menuList.get(0).getMenuComponent();
        }
        request.setAttribute("menu",mMenu);
        request.setAttribute("activeName",activeName);
        request.setAttribute("menulist",menuList);
        return "page/menu_model";
    }

    @GetMapping("/nav")
    public String navController(){
        return "nav/main.html";
    }

    @GetMapping("/zy")
    public String searchController(){
        return "zy";
    }

    @GetMapping("/video")
    public String getVideo(){
        return "video";
    }
}
